import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  getSearchResultAction,
  updateSearchResultAction,
} from '@/store/action/search';
import { InfiniteScroll } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const { search } = useLocation();
  const searchParams = new URLSearchParams(search);
  // 获取 URL 的查询参数 q 的值
  const q = (searchParams.get('q') || '') as string;
  console.log('获取查询参数q的值', q);
  const dispatch = useDispatch();
  const { resultsData } = useAppSelector((state) => state.search);
  const { results, page, total_count } = resultsData;
  console.log('results  ----->  ', results);
  useEffect(() => {
    dispatch(getSearchResultAction(q));
  }, [q, dispatch]);
  // 组件卸载时,清除redux中的数据
  useEffect(() => {
    return () => {
      // 修复卸载的逻辑
      dispatch({ type: 'search/saveResults', payload: {} });
    };
  }, [dispatch]);
  const loadMore = async () => {
    await console.log('111');
    // 5 loadMore触发异步action
    await dispatch(updateSearchResultAction(q, page + 1));
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => {
          return <ArticleItem key={item.art_id} data={item} />;
        })}
      </div>
      {/* 6. 通过条件渲染，处理两次请求重复的问题*/}
      {!!results.length && (
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={results.length < total_count}
        />
      )}
    </div>
  );
}
